#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "StdUDP.h"

struct UdpServer
{
    int sock;
};

UdpS *InitUdpServer(const char *IP, short int port)
{
    UdpS *s = (UdpS *)malloc(sizeof(UdpS));
    if(s == NULL)
    {
        printf("InitUdpServer malloc error!\n");
        return NULL;
    }
    s->sock = socket(AF_INET,SOCK_DGRAM,0);
    if(s->sock < 0)
    {
        perror("socket():");
        free(s);
        return NULL;
    }
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(IP);
    

    if(bind(s->sock,(struct sockaddr*)&addr,sizeof(addr)) != 0)
    {
        perror("bind()");
        free(s);
        return NULL;
    }
    return s;
}

void UdpServerSend(UdpS *s,const char *destIP, short int port, void *ptr, size_t size)
{
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(destIP);
    if(sendto(s->sock,ptr,size,0,(struct sockaddr*)&addr,sizeof(addr)) < 0)
    {
        perror("UdpServerSend sendto():");
    }
}


void UdpServerReceive(UdpS *s,void *ptr, size_t size)
{
    struct sockaddr_in addr;
    socklen_t len;
    if(recvfrom(s->sock,ptr,size,0,(struct sockaddr*)&addr,&len) < 0)
    {
        perror("UdpServerReceive recvfrom:");
    }
}


void ClearUdpServer(UdpS *s)
{
    close(s->sock);
    free(s);
}






struct UdpClient
{
    int sock;
    char ServerIP[20];
    short int ServerPort;
};


UdpC *InitUdpClient(const char *ServerIP, short int ServerPort)
{   UdpC *c = (UdpC *)malloc(sizeof(UdpC));
    if(c == NULL)
    {
        printf("InitUdpServer malloc error!\n");
        return NULL;
    }
    
    c->sock = socket(AF_INET,SOCK_DGRAM,0);

    if(c->sock < 0)
    {
        perror("bind()");
        free(c);
        return NULL;
    }
    strcpy(c->ServerIP,ServerIP);
    c->ServerPort = ServerPort;
    return c;
}

void UdpClisentSend(UdpC *c,void *ptr, size_t size)
{
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(c->ServerPort);
    addr.sin_addr.s_addr = inet_addr(c->ServerIP);
    if(sendto(c->sock,ptr,size,0,(struct sockaddr*)&addr,sizeof(addr)) < 0)
    {
        perror("UdpClisentSend sendto():");
    }
}

void UdpClientReceive(UdpC *c, void *ptr, size_t size)
{
    struct sockaddr_in addr;
    socklen_t len;
    if(recvfrom(c->sock,ptr,size,0,(struct sockaddr*)&addr,&len) < 0)
    {
        perror("UdpClientReceive recvfrom:");
    }
}

void ClearUdpClient(UdpC *c)
{
    close(c->sock);
    free(c);
}
